﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Basic.Model.Entity;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;

namespace Basic.Model.EntityManager
{
    public class AdminGroupManager
    {
        public static void Add(ISession session, AdminGroup an)
        {
            session.Save(an);
        }

        public static void Delete(ISession session, AdminGroup an)
        {
            session.Delete(an);
        }

        public static void Update(ISession session, AdminGroup an)
        {
            session.Update(an);
        }

        public static AdminGroup Get(ISession session, int itemId)
        {
            return session.Get<AdminGroup>(itemId);
        }

        public static AdminGroup GetByCondition(ISession session, int groupId, string groupName, bool isAdmin, bool isRole)
        {
            ICriteria c = session.CreateCriteria(typeof(AdminGroup));
            if (groupId >= 0)
                c.Add(Expression.Eq("groupId", groupId));
            if (!String.IsNullOrEmpty(groupName))
                c.Add(Expression.Eq("groupName", groupName));
            if(isAdmin)
                c.SetFetchMode("admins", FetchMode.Select);
            return c.UniqueResult<AdminGroup>();
        }

        public static IList<AdminGroup> GetAll(ISession session)
        {
            ICriteria c = session.CreateCriteria(typeof(AdminGroup));
            c.AddOrder(Order.Asc("groupId"));
            return c.List<AdminGroup>();
        }

        public static IList<AdminGroup> GetAllByCondition(ISession session, bool isAdmin, bool isRole, int rowIndex, int rowCount)
        {
            ICriteria c = session.CreateCriteria(typeof(AdminGroup));
            if (rowIndex >= 0)
                c.SetFirstResult(rowIndex);
            if (rowCount >= 0)
                c.SetMaxResults(rowCount);
            if (isAdmin)
                c.SetFetchMode("admins", FetchMode.Select);
            if (isRole)
                c.SetFetchMode("roles", FetchMode.Select);
            if (isAdmin || isRole)
                c.SetResultTransformer(NHibernate.CriteriaUtil.DistinctRootEntity);
            c.AddOrder(Order.Asc("groupId"));
            return c.List<AdminGroup>();
        }
        public static int GetAllByConditionCount(ISession session)
        {
            ICriteria c = session.CreateCriteria(typeof(AdminGroup));
            return (int)c.SetProjection(Projections.Count("groupId")).UniqueResult();
        }
    }
}
